<script setup>
import { computed, inject, onMounted, ref, toRaw, watch } from "vue";
//图标组件
import {IconArrowLeft, IconDecreaseCircle, IconPlusCircle, IconCarShipping, IconCrossCircle} from '../icon/index.js'
//消息提示工具
import {DlMessageBox} from '../util/messagebox.js'
import DlLoading from '../components/DlLoading.vue'

//引入 api
import { getUserDefaultAddrFun } from '../api/user.js'
import { getUserCartFun, removeFormCartFun, modifyFromCartFun } from '../api/cart.js'
import { addUserOrderFun } from '../api/order.js'

//是否可编辑
const editing = ref(false);
function doEdit() {
    editing.value = !editing.value;
}

// view-content-dl height = 底部菜单 offsetTop - 顶部菜单 offsetHeight
const viewHead = ref(null);
const viewMenuBar = ref();
const viewHeight = computed(()=>{
    if(viewMenuBar.value && viewHead.value ) {
        return viewMenuBar.value.offsetTop - viewHead.value.offsetHeight - 10;
    }
    return 400;
});


//购物车 模拟数据
const cart = inject('cart');
//购物车数据
const cartId = ref();
const cartArr = ref([]);
const loading = ref(false);
//加载购物车数据
function doLoadData() {
    //登录后才能加载购物车
    if(!isLogin.value) return;
    loading.value = true;
    //发请求加载购物车数据
    //console.log('cart:', cart);

    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            if(cart) {
                cartId.value = 123;
                cartArr.value = [];
                for(let k in cart) {
                    // 购物车中元素的主要结构 {productId, image, title, type, selectType, price, num}
                    let c = cart[k];
    
                    //模拟下架展示效果
                    // c.status = Math.random() > 0.5 ? -1 : 1;
    
                    //秒杀商品判断(如果是秒杀商品,则需要有额外属性 endTime,表示该商品对应的秒杀活动的结束时间)
                    c.expired = false;
                    c.expireTxt = '';
                    if(c.status == -1) {
                        c.expired = true;
                        c.expireTxt = '商品已下架';
                    } else if(c.endTime) {
                        //是否过期, true过期
                        c.expired = c.endTime <= Date.now();
                        c.expireTxt = c.expired ? '商品已过期':'';
                    }
    
                    if(c.selectType === undefined || c.selectType === null) {
                        c.selectType = '';
                    }
                    //JS处理 选中效果
                    c.checked = false;
                    cartArr.value.push(c);
                }
            }
            loading.value = false;
        }, 1000);
    } else {
        //请求api
        getUserCartFun().then((result)=>{
            console.log('getUserCartFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
                let data = result.data;
                cartId.value = data.id;
                let cart = data.list;
                cartArr.value = [];
                for(let k in cart) {
                    // 购物车中元素的主要结构 {productId, image, title, type, selectType, price, num}
                    let c = cart[k];
    
                    //秒杀商品判断(如果是秒杀商品,则需要有额外属性 endTime,表示该商品对应的秒杀活动的结束时间)
                    c.expired = false;
                    c.expireTxt = '';
                    if(c.status == -1) {
                        c.expired = true;
                        c.expireTxt = '商品已下架';
                    } else if(c.endTime) {
                        //是否过期, true过期
                        c.expired = c.endTime <= Date.now();
                        c.expireTxt = c.expired ? '商品已过期':'';
                    }
    
                    if(c.selectType === undefined || c.selectType === null) {
                        c.selectType = '';
                    }
                    //JS处理 选中效果
                    c.checked = false;
                    cartArr.value.push(c);
                }
            } else {
                DlMessageBox.error(result.msg);
            }
            loading.value = false;
        });
    }
}

//选中、统计等处理
const cartObj = computed(()=>{
    let checkAll = true;
    for(let c of cartArr.value) {
        if(!c.checked) {
            checkAll = false;
        }
        if(c.endTime && !c.expired) {
            console.log(toRaw(c));
            //是否过期, true过期
            c.expired = c.endTime <= Date.now();
            c.expireTxt = c.expired ? '商品已过期':'';
            if(c.expired) {
                c.checked = false;//不能选中
            }
        }
    }
    if(cartArr.value.length < 1) {
        checkAll = false;//空数组
    }
    let reduceObj = cartArr.value.reduce((p, c)=>{
        if(c.checked) {
            //计算不精确的处理
            p.total += (c.price*100*c.num);
            p.num+=c.num;
        }

        return p;
    }, {total: 0, num: 0});
    let num = reduceObj.num;
    if(num>99) {
        num = '99+';
    }
    //console.log('cartArr.value:', cartArr.value, ',checkAll:', checkAll);
    return { checkAll, num: num, total: (reduceObj.total/100).toFixed(2) };
});
function doCheckAll(flag) {//全选操作
    for(let c of cartArr.value) {
        c.checked = flag;
    }
}
//删除购物车中选中的
function doRemoveCheck() {
    //删除选中
    let removeArr = cartArr.value.filter(c=>c.checked);
    let removeIdArr = removeArr.map(c=>c.productId);
    let params = {
        cartId: cartId.value,
        productIdArr: removeIdArr
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        //页面效果操作
        let arr = cartArr.value.filter(c=>!c.checked);
        cartArr.value = arr;
        editing.value = false;

        //成功后执行以下操作
        DlMessageBox.success('删除成功');
    } else {
        //请求api
        removeFormCartFun(params.cartId, params.productIdArr).then((result)=>{
            console.log('removeFormCartFun result:', result);
            if (result.code == 200) {
                //页面效果操作
                let arr = cartArr.value.filter(c=>!c.checked);
                cartArr.value = arr;
                editing.value = false;

                DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}

//修改购物车中数量
function doDecreaseNum(c) {
    //TODO: 数量修改-减少
    let params = {
        cartId: cartId.value,
        productId: c.productId,
        num: c.num - 1,
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        //页面效果操作
        c.num--;
        if(c.num < 1) {
            //删除
            let arr = cartArr.value.filter(p => p.productId!=c.productId);
            cartArr.value = arr;
        }
        //成功后执行以下操作
        //DlMessageBox.success('数量修改成功');
    } else {
        //请求api
        modifyFromCartFun(params.cartId, params.productId, params.num).then((result)=>{
            console.log('modifyFromCartFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
                //页面效果操作
                c.num--;
                if(c.num < 1) {
                    //删除
                    let arr = cartArr.value.filter(p => p.productId!=c.productId);
                    cartArr.value = arr;
                }
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}
function doPlusNum(c) {
    //数量修改-增加
    let params = {
        cartId: cartId.value,
        productId: c.productId,
        num: c.num + 1,
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        c.num++;
    } else {
        //请求api
        modifyFromCartFun(params.cartId, params.productId, params.num).then((result)=>{
            console.log('modifyFromCartFun result:', result);
            if (result.code == 200) {
                //成功后执行以下操作
                //DlMessageBox.success(result.msg);
                c.num++;
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//从购物车中删除过期/下架商品
function doRemoveExpire(c) {
    //删除
    let params = {
        cartId: cartId.value,
        productIdArr: [ c.productId ],
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        //页面效果操作
        let index = cartArr.value.findIndex(d => d.productId == c.productId);
        if (index != -1) {
            cartArr.value.splice(index, 1);
        }

        //成功后执行以下操作
        DlMessageBox.success('删除成功');
    } else {
        //请求api
        removeFormCartFun(params.cartId, params.productIdArr).then((result)=>{
            console.log('removeFormCartFun result:', result);
            if (result.code == 200) {
                //页面效果操作
                let index = cartArr.value.findIndex(d => d.productId == c.productId);
                if (index != -1) {
                    cartArr.value.splice(index, 1);
                }
                DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//用户修改 选择的 规格参数
function doTypeChanged(c) {
    //console.log(c);
    let params = {
        cartId: cartId.value,
        productId: c.productId,
        selectType: c.selectType,
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        //成功后执行以下操作
        DlMessageBox.success('修改成功');
    } else {
        //请求api
        modifyFromCartFun(params.cartId, params.productId, undefined, params.selectType).then((result)=>{
            console.log('modifyFromCartFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//主页底部菜单
const menuCore = inject('menuCore');
function doGoBack() {//菜单 返回
    menuCore.back();
}

//添加订单
function doAddOrder() {
    //console.log('cart:', cart);
    if(!isLogin.value) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        menuCore.push('/user');
        return;
    }

    //选中的
    let idArr = [];
    //剩余的
    let restArr = [];
    //结算选中
    for(let i=0;i<cartArr.value.length;i++) {
        let c = cartArr.value[i];
        if(c.checked) {
            if(!c.selectType) {
                DlMessageBox.warning('有商品未选择规格');
                return;
            }
            idArr.push(c.productId);
        } else {
            restArr.push(c);
        }
    }
    if(idArr.length < 1) {
        DlMessageBox.warning('请选择购买的商品');
        return;
    }

    //下单(结算)
    let params = {
        name: defaultAddr.value.name,
        phone: defaultAddr.value.phone,
        addr: defaultAddr.value.addr,
        cartId: cartId.value,
        productIdArr: idArr,
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        //成功后执行以下操作
        DlMessageBox.success('下单成功');
        //跳转到支付
        localStorage.setItem('orderId', 2);
        menuCore.push('/pay');
    } else {
        //请求api
        addUserOrderFun(params.name, params.phone, params.addr, params.cartId, params.productIdArr).then((result)=>{
            console.log('addUserOrderFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //跳转到支付
                localStorage.setItem('orderId', result.data);
                menuCore.push('/pay');
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//去详情
function doDetail(productId) {
    localStorage.setItem('detailProductId', productId);
    menuCore.push('/detail');
}

//获取默认地址
const defaultAddr = ref({name:'', phone:'', addr:''});
function doLoadDefaultAddr() {
    //未登录
    if(!isLogin.value) return;
    // 获取当前用户的默认地址
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let addrObj = {name:'张先生', phone:'13912345678', addr:'江苏省南京市江北新区XXXXXX社区XXXXX路XX号XXXX小区XX栋XXX室'};
            // 成功后执行以下操作
            defaultAddr.value = addrObj;
        }, 500);
    } else {
        //请求api
        getUserDefaultAddrFun().then((result)=>{
            console.log('getUserDefaultAddrFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
                defaultAddr.value = result.data;
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//登录用户缓存
const loginUser = inject('loginUser');
const isLogin = ref(false);
function doCheckLogin() {
    if(!loginUser.value || !loginUser.value.token) {
        DlMessageBox.error('您还未登录,\n请先登录!');

        // 页面可临时操作, 未做登录后的数据同步
        //menuCore.push('/user');
        return;
    }
    isLogin.value = true;
}

onMounted(()=>{
    doCheckLogin();
    doLoadData();
    doLoadDefaultAddr();
});

</script>
<template>
    <div class="view-dl">
        <div class="view-head-dl" ref="viewHead">
            <div class="left-item-dl">
                <IconArrowLeft class="icon-dl" @click="doGoBack" />
                <span class="title-dl" >购物车</span>
            </div>
            <div class="tools-dl" @click="doEdit" >{{editing?'完成':'编辑'}}</div>
        </div>
        <div class="view-content-dl" :style="'height:'+viewHeight+'px'">
            <!-- 收货地址 -->
            <div class="addr-box-dl">
                <div class="addr-info-dl" v-show="!isLogin" style="text-align:center;color:#900;cursor:pointer;" @click="menuCore.push('/login')" >未登录, 去登录</div>
                <div class="addr-icon-dl" v-show="isLogin">
                    <IconCarShipping class="icon-dl" />
                </div>
                <div class="addr-info-dl" v-show="isLogin">
                    <div class="user-box-dl">
                        <div class="name-dl">{{defaultAddr.name}}</div>
                        <div class="phone-dl">{{defaultAddr.phone}}</div>
                    </div>
                    <div class="addr-dl">{{defaultAddr.addr}}</div>
                </div>
                <div class="addr-select-dl" v-show="isLogin" @click="menuCore.push('/useraddr')" >选择</div>
            </div>

            <!-- 商品 -->
            <div class="cart-list-dl">
                <div class="cart-item-dl" v-for="c in cartArr" :key="c.productId">
                    <div class="item-check-dl" >
                        <input type="checkbox" v-model="c.checked">
                    </div>
                    <div class="item-img-dl" @click="doDetail(c.productId)">
                        <img :src="c.image" alt="no image">
                    </div>
                    <div class="item-body-dl">
                        <div class="item-body-title-dl" @click="doDetail(c.productId)" >{{c.title}}</div>
                        <div class="item-body-type-dl" >
                            <span>规格：</span>
                            <!-- <span>{{c.selectType ? c.selectType : '请选择规格'}}</span> -->
                            <select class="type-select-dl" v-model="c.selectType" @change="doTypeChanged(c)">
                                <option value="" >请选择规格</option>
                                <option :value="t" v-for="t in c.type" :key="t">{{t}}</option>
                            </select>
                        </div>
                        <div class="item-body-tips-dl">
                            <div class="item-price-dl">￥{{c.price}}</div>
                            <div class="item-act-dl" >
                                <span class="icon-dl" @click="doDecreaseNum(c)"><IconDecreaseCircle/></span>
                                <span class="num-dl" >{{c.num}}</span>
                                <span class="icon-dl" @click="doPlusNum(c)"><IconPlusCircle/></span>
                            </div>
                        </div>
                    </div>

                    <div class="expired-box-dl" v-show="c.expired" >
                        <div class="tip-dl">{{c.expireTxt}}</div>
                        <div class="btn-dl" @click="doRemoveExpire(c)">
                            <IconCrossCircle class="icon-dl" />
                        </div>
                    </div>
                </div>
            </div>

            <!-- 加载中动画... -->
            <div class="load-box-dl" >
                <DlLoading style="font-size: 1rem" v-show="loading" />
                <div class="no-more-data-dl" v-show="!loading && cartArr.length < 1">购物车空空的</div>
            </div>

        </div>
        <div class="bottom-menu-bar-dl" ref="viewMenuBar">
            <div class="item-check-dl" >
                <input type="checkbox" @click="doCheckAll($event.target.checked)" :checked="cartObj.checkAll" >
                <span>全选</span>
            </div>
            <div class="tools-dl">
                <div v-if="editing" class="remove-dl" @click="doRemoveCheck">删除</div>
                <template v-else >
                    <div class="total-price-dl">
                        <span>总计：</span>
                        <span class="money" >￥{{cartObj.total}}</span>
                    </div>
                    <div class="done-dl" @click="doAddOrder">结算({{cartObj.num}})</div>
                </template>
            </div>
        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    overflow: hidden auto;
}
.view-head-dl {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.1rem 0.2rem;
    border-bottom: 1px solid #eee;
    background-color: #fff;
    color: #000;
}
.view-head-dl .left-item-dl {
    font-size: 0.7rem;
}
.left-item-dl .icon-dl {
    width: 0.8rem;
    height: 0.8rem;
    vertical-align: bottom;
    cursor: pointer;
}
.left-item-dl .title-dl {
    height: 0.92rem;
    display: inline-block;
    padding-left: 0.2rem
}
.view-head-dl .tools-dl { 
    cursor: pointer;
    color: #909399;
    font-size: 0.48rem;
}
.view-content-dl {
    padding: 0.1rem 0.2rem;
    overflow: hidden auto;
}

.addr-box-dl {
    font-size: 0.4rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    color: #333;
    font-weight: bold;
    border-radius: 0.2rem;
    padding: 0.1rem;
    margin: 0.2rem 0;
}
.addr-icon-dl {
    width: 1rem;
    height: 1rem;
    color: #999;
    text-align: center;
    flex-shrink: 0;
}
.addr-info-dl {
    flex: 1 0 0;
    margin: 0 0.2rem;
}
.user-box-dl {
    margin: 0.2rem 0;
}
.user-box-dl .name-dl {
    display: inline-block;
    margin-right: 0.6rem;
}
.user-box-dl .phone-dl {
    display: inline-block;
}
.addr-info-dl .addr-dl {
    margin: 0.2rem 0;
}
.addr-select-dl {
    flex-shrink: 0;
    color: #999;
    padding: 0.2rem;
    cursor: pointer;
    font-size: 0.4rem;
}

.cart-list-dl {
    margin: 0.1rem 0;
}

.cart-item-dl {
    display: flex;
    align-items: center;
    margin-bottom: 0.2rem;
    background-color: #fff;
    border-radius: 0.2rem;
    padding: 0.08rem 0.2rem;
    color: #333;
    position: relative;
}
.item-check-dl {
    flex-shrink: 0;
    width: 0.72rem;
}
.item-check-dl [type=checkbox] {
    width: 0.4rem;
    height: 0.4rem;
}
.item-img-dl {
    width: 2.4rem;
    height: 2.4rem;
    margin-right: 0.2rem;
    flex-shrink: 0;
    cursor: pointer;
}
.item-img-dl img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.4rem;
    display: block;
}
.item-body-dl {
    overflow: hidden;
    flex: 1 1 auto;
    font-size: 0.4rem;
}
.item-body-title-dl {
    overflow: hidden;
    text-overflow: ellipsis;
    /* white-space: nowrap; */
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    cursor: pointer;
}
.item-body-type-dl {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin: 0.08rem 0;
    color: #999;
}
.type-select-dl {
    width: 2rem;
    height: 0.48rem;
    font-size: 0.3rem;
    vertical-align: bottom;
}
.item-body-tips-dl {
    display: flex;
    justify-content: space-between;
    font-size: 0.4rem;
}
.item-price-dl {
    color: #d90000;
    font-weight: bold;
}
.item-act-dl {
    display: flex;
    justify-items: center;
}

.item-act-dl .num-dl {
    padding: 0 0.3rem;
    font-size: 0.46rem;
}

.item-act-dl .icon-dl {
    display: inline-block;
    width: 0.6rem;
    cursor: pointer;
}

.expired-box-dl {
    font-size: 0.6rem;
    font-weight: bold;
    color: #c00;
    position: absolute;
    background-color: #ccc9;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1;
    border-radius: 0.2rem;
}
.expired-box-dl .tip-dl {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.expired-box-dl .btn-dl {
    position: absolute;
    width: 0.8rem;
    font-size: 0.52rem;
    top: 0;
    bottom: 0;
    right: 0;
    background-color: #a009;
    color: #fff;
    padding: 0.2rem;
    border-radius: 0 0.2rem 0.2rem 0;
    cursor: pointer;
}
.expired-box-dl .btn-dl .icon-dl {
    width: 1rem;
    height: 1rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.load-box-dl {
    text-align: center;
    color: #aaa;
    margin-top: 1rem;
}
.load-box-dl .no-more-data-dl {
    font-size: 0.6rem;
}

.bottom-menu-bar-dl {
    width: 100%;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.1rem 0.2rem;
    box-sizing: border-box;
    font-size: 0.4rem;
    color: #333;
}
.bottom-menu-bar-dl .item-check-dl {
    overflow: hidden;
    width: 1.4rem;
}
.bottom-menu-bar-dl .tools-dl {
    display: flex;
    align-items: center;
}
.total-price-dl {
    margin-right: 0.3rem;
}
.total-price-dl .money {
    color: #d90000;
    font-weight: bold;
}
.bottom-menu-bar-dl .done-dl {
    background-color: #d90000;
    color: #fff;
    padding: 0.08rem 0.28rem;
    border-radius: 1rem;
    width: 2rem;
    text-align: center;
    cursor: pointer;
}
.bottom-menu-bar-dl .done-dl:hover {
    background-color: #a90000;
}
.bottom-menu-bar-dl .remove-dl {
    background-color: #fff;
    color: #333;
    padding: 0.08rem 0.28rem;
    border-radius: 1rem;
    border: 1px solid #ccc;
    width: 2rem;
    text-align: center;
    cursor: pointer;
}
.bottom-menu-bar-dl .remove-dl:hover {
    background-color: #f0f0f0;
}

</style>